const { getDb } = require('../database');

class ReleaseListModel {
  /**
   * 获取所有发布列表项
   * @returns {Promise<Array>} 发布列表项
   */
  static async getAllReleaseList() {
    const db = await getDb();
    return db.all('SELECT * FROM release_list');
  }

  /**
   * 根据ID获取发布列表项
   * @param {number} id - 发布列表项ID
   * @returns {Promise<Object|null>} 发布列表项信息
   */
  static async getReleaseListById(id) {
    const db = await getDb();
    return db.get('SELECT * FROM release_list WHERE id = ?', [id]);
  }

  /**
   * 根据新闻ID获取发布列表项
   * @param {number} newsId - 新闻ID
   * @returns {Promise<Object|null>} 发布列表项信息
   */
  static async getReleaseListByNewsId(newsId) {
    const db = await getDb();
    return db.get('SELECT * FROM release_list WHERE news_id = ?', [newsId]);
  }

  /**
   * 创建发布列表项
   * @param {Object} releaseListData - 发布列表项数据
   * @returns {Promise<number>} 新创建的发布列表项ID
   */
  static async createReleaseList(releaseListData) {
    const { news_id, abstract_real, class_real, title, site_name, create_time, op_person, is_select, order_news } = releaseListData;
    const db = await getDb();
    const result = await db.run(
      'INSERT INTO release_list (news_id, abstract_real, class_real, title, site_name, create_time, op_person, is_select, order_news) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [news_id, abstract_real, class_real, title, site_name, create_time, op_person, is_select || 1, order_news || 0]
    );
    return result.lastID;
  }

  /**
   * 更新发布列表项
   * @param {number} id - 发布列表项ID
   * @param {Object} releaseListData - 发布列表项数据
   * @returns {Promise<boolean>} 是否更新成功
   */
  static async updateReleaseList(id, releaseListData) {
    const { news_id, abstract_real, class_real, title, site_name, create_time, op_person, is_select, order_news } = releaseListData;
    const db = await getDb();
    const result = await db.run(
      'UPDATE release_list SET news_id = ?, abstract_real = ?, class_real = ?, title = ?, site_name = ?, create_time = ?, op_person = ?, is_select = ?, order_news = ? WHERE id = ?',
      [news_id, abstract_real, class_real, title, site_name, create_time, op_person, is_select, order_news, id]
    );
    return result.changes > 0;
  }

  /**
   * 删除发布列表项
   * @param {number} id - 发布列表项ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  static async deleteReleaseList(id) {
    const db = await getDb();
    const result = await db.run('DELETE FROM release_list WHERE id = ?', [id]);
    return result.changes > 0;
  }

  /**
   * 更新发布列表项的排序
   * @param {number} id - 发布列表项ID
   * @param {number} order - 排序值
   * @returns {Promise<boolean>} 是否更新成功
   */
  static async updateOrder(id, order) {
    const db = await getDb();
    const result = await db.run('UPDATE release_list SET order_news = ? WHERE id = ?', [order, id]);
    return result.changes > 0;
  }
}

module.exports = ReleaseListModel;